#include "../header.h"


int main() {
    int fd;
    char buffer[1024];
    char *input_str, *ptr;
    long offset;
    ssize_t bytes_read;

    // 打开文件
    fd = open("poem.txt", O_RDWR | O_CREAT, 0644);
    if (fd == -1) {
        perror("Error opening file");
        exit(EXIT_FAILURE);
    }

    // 读取文件内容
    bytes_read = read(fd, buffer, sizeof(buffer) - 1);
    if (bytes_read == -1) {
        perror("Error reading file");
        exit(EXIT_FAILURE);
    }
    buffer[bytes_read] = '\0';

    // 查找第一个 ( 的位置
    ptr = strstr(buffer, "(");
    if (ptr == NULL) {
        printf("No parentheses found in the file.\n");
        exit(EXIT_FAILURE);
    }

    // 获取用户输入
    printf("Enter the text you want to insert: ");
    input_str = malloc(1024);
    if (fgets(input_str, 1023, stdin) == NULL) {
        perror("Error reading input");
        exit(EXIT_FAILURE);
    }
    input_str[strcspn(input_str, "\n")] = 0;  // 移除 fgets 读取的换行符

    // 计算插入位置
    offset = ptr - buffer + 1;

    // 定位到插入位置
    if (lseek(fd, offset, SEEK_SET) == -1) {
        perror("Error seeking file");
        exit(EXIT_FAILURE);
    }

    // 写入用户输入的话
    if (write(fd, input_str, strlen(input_str)) == -1) {
        perror("Error writing to file");
        exit(EXIT_FAILURE);
    }

    printf("Text inserted successfully.\n");

    // 关闭文件
    close(fd);
    free(input_str);

    return 0;
}